package com.four.bmm.controller;

import com.four.bmm.entity.News;
import com.four.bmm.service.NewsService;
import com.four.bmm.util.JsonUtil;
import com.four.bmm.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/AdminNewsByPageServlet")
public class AdminNewsByPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("开始查询数据...");
        // 1.获得页面数据
        String pageIndex =request.getParameter("pageIndex"); // 当前页
        if (pageIndex == null) {
            pageIndex = "1";
        }
        Integer pageNo = Integer.parseInt(pageIndex);
        String keyword=request.getParameter("keyword");      //关键词
        //2.调用service层的服务
        NewsService newsService = new NewsService();
        //3.计算总记录数
        int totalRows=newsService.NewsCount(keyword) ;
        //4.计算总页数
        int totalPage = PageUtil.getToatlPages(totalRows);
        PageUtil pageUtil=new PageUtil();
        //5.分页显示的数据
        List<News> newsList = newsService.GetAllNews(pageNo,keyword);
        Map<String, Object> map = new HashMap<>();
        map.put("newsList",  newsList);
        map.put("totalPage", totalPage);
        map.put("totalRows", totalRows);
        map.put("currentResult", pageNo);
        JsonUtil.toJson(response,map);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
